/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package socketHandler;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.Scanner;

/**
 *
 * @author Александр Емельянов (mr.lex91@gmail.com)
 */
public class MessageSocketHandler{
    private Socket socket;
    private Scanner scan;
    public MessageSocketHandler(Socket socket) throws IOException
    {
        this.socket=socket;
        scan=new Scanner(new InputStreamReader(socket.getInputStream(),"UTF-8"));
    }
    public void Write(String msg) throws IOException
    {
        synchronized(socket)
        {
            socket.getOutputStream().write((msg+"\n<END>\n").getBytes("UTF-8"));
        }
    }
    public String Read() throws IOException
    {
        String msg="";
        while (scan.hasNextLine())
        {
            String part=scan.nextLine();
            if (part.equalsIgnoreCase("<END>"))break;
            msg+=((msg.length()==0)?"":"\n")+part;
        }
        return msg;
    }
    public void Close()
    {
        try {
            if (socket!=null)
            {
                socket.close();
                socket=null;
            }
        } catch (IOException ex) {}
    }
    public String inetInfo()
    {
        return "Host: "+socket.getLocalAddress().getHostAddress()+"\nPort: "+socket.getLocalPort();
    }
}
